package com.touchfired.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;

import java.net.URLDecoder;

/**
 * socket通道连接参数处理器
 *
 * @author 幸佳俊
 */
public class WebSocketPreConnectHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            HttpHeaders headers = request.headers();
            if (null != uri && uri.contains("?")) {
                String[] uriArray = uri.split("\\?");
                if (uriArray.length > 1) {
                    String[] paramsArray = uriArray[1].split("&");
                    for (int i = 0; i < paramsArray.length; i++) {
                        String paramsEntry = paramsArray[i];
                        String[] entryArray = paramsEntry.split("=");
                        if (entryArray.length > 1) {
                            if (!headers.contains(entryArray[0])) {
                                headers.add(entryArray[0], URLDecoder.decode(entryArray[1], "UTF-8"));
                            }
                        }
                    }
                }
                request.setUri("/ws");
            }
        }
        super.channelRead(ctx, msg);
    }
}
